var WFServerList = new Class({
    Implements: [Options, Events],
    table_id: 'server_list',
    status_img: '<img class="status_img" src="' + homeBase + 'img/default/widgetLoading.gif" />',
    refresh_icon: homeBase + 'img/default/icon_refresh.gif',
    lost_connection: [],
    timeout_connection: [],
    adding: false,
    firstproxyid: null,
    hasProxy: false,
    scanservercheckarray: {},
    proxylistcheckarray: null,
    serverlistcheckarray: null,
    NeedToopenOpts: false,
    objSelectedServerHash: new Hash(),
    msg: null,
    showServerTypeColumn:true,
    supportServerTypes:[],

    initialize: function(customOption){
        if (customOption){
            if (typeof customOption.showServerTypeColumn !== 'undefined' && typeof customOption.showServerTypeColumn === 'boolean'){
                this.showServerTypeColumn = customOption.showServerTypeColumn;
            }
            if (typeof customOption.supportServerTypes !== 'undefined'){
                if (customOption.supportServerTypes instanceof Array){
                    this.supportServerTypes = customOption.supportServerTypes;
                } else if (typeof customOption.supportServerTypes === 'string'){
                    this.supportServerTypes = new Array(customOption.supportServerTypes);
                }
            }
        }
        this.renderUI();
    },
    showMsg: function(msg, type){
        this.errormsg = $('messageBox');
        this.msg = new WFMessage(this.errormsg);
        var option = {
            type: '0', //0: error, 1: warn, 2: info
            description: msg //text
        };
        this.msg.fireEvent('message',option);
        this.severlistModal.onResize();
    },
    updateNotesLocation:function(){
    },
    /////// load the info in the box
    onFinish: function () {
        var lastupdate = lang.label('last_check') + new Date().formatDate(lang.label('dateformat'));
        var HTML = [
            '<div id="messageBox"></div>',
            '<div id="serverlist_setting">',
            '   <div class="hd">',
            '       <div class="panel clearfix">',
            '           <div class="option clearfix">',
            '               <div class="button first" id="add_server">',
            '                   <div class="left"></div>',
            '                   <div class="mid"><a href="#" class="add_server">'+lang.label('btn_add')+'</a></div>',
            '                   <div class="right"></div>',
            '               </div>',
            '               <div class="button" id="del_server">',
            '                   <div class="left"></div>',
            '                   <div class="mid"><a href="#" class="del_server">'+lang.label('btn_delete')+'</a></div>',
            '                   <div class="right"></div>',
            '               </div>',
            '               <div class="button" id="refresh_server">',
            '                   <div class="left"></div>',
            '                   <div class="mid"><a href="#" class="refresh">'+lang.label('refresh')+'</a></div>',
            '                   <div class="right"></div>',
            '               </div>',
            '           </div>',
            '           <div class="lastupdate">',
            '               <span id="updateText">'+lastupdate+'</span>',
            '           </div>',
            '       </div>',
            '       <div class="servers">',
            '       <table class="serverlist" id="server_list">',
            '           <tbody>',
            '               <tr>',
            '                   <th class="check"><input type="checkbox" id="checkAll"></th>',
            '                   <th class="title">'+lang.label('cloud_url')+'</th>',
            '                   ' + ((this.showServerTypeColumn === true) ? '<th class="type">'+lang.label('type')+'</th>' : ''),
            '                   <th class="edit">'+lang.label('edit')+'</th>',
            '               </tr>',
            /*
            '               <tr>',
            '                   <td><input type="checkbox" class="select"></td>',
            '                   <td><span class="online">localhost</span></td>',
            '                   <td>Widget Framework</td>',
            '                   <td><a href="#" class="edit"></a></td>',
            '               </tr>',
            */
            '           </tbody>',
            '       </table>',
            '       </div>',
            '       <div class="addserver">',
            /*
            '           <table>',
            '               <tbody>',
            '                   <tr>',
            '                       <td>'+lang.label('server_name')+':</td>',
            '                       <td><input type="text" class="server_name text"></td>',
            '                   </tr>',
            '                   <tr>',
            '                       <td></td>',
            '                       <td><span class="example">'+lang.label('server_example')+'</span></td>',
            '                   </tr>',
            '                   <tr>',
            '                       <td>'+lang.label('account')+':</td>',
            '                       <td><input type="text" class="account_text"></td>',
            '                   </tr>',
            '                   <tr>',
            '                       <td>'+lang.label('Password')+':</td>',
            '                       <td><input type="text" class="password text"></td>',
            '                   </tr>',
            '                   <tr>',
            '                       <td></td>',
            '                       <td class="cleafix"><div class="ui-button clearfix save"><div class="left"></div><div class="mid">'+lang.label('btn_save')+'</div></div><div class="ui-button clearfix cancel"><div class="left"></div><div class="mid">'+lang.label('btn_cancel')+'</div></div></td>',
            '                   </tr>',
            '               </tbody>',
            '           </table>',
            */
            '       </div>',
            '       <div class="proxyserver">',
            '           <div class="title clearfix">',
            '               <h3>'+lang.label('proxy_setting')+'</h3><a href="#" class="off" id="proxy_toggle"></a>',
            '           </div>',
            '           <div class="form" id="proxy_content">',
            '               <table>',
            '                   <tbody>',
            '                       <tr>',
            '                           <td class="check"><input type="checkbox" id="enable_proxy"></td>',
            '                           <td colspan="2"><label for="enable_proxy">'+lang.label('use_a_proxy')+'</label></td>',
            '                       </tr>',
            '                       <tr>',
            '                           <td></td>',
            '                           <td class="second">'+lang.label('proxy_protocol')+'</td>',
            '                           <td><input id="protocol_http" type="radio" checked="checked" name="protocol"> <label for="protocol_http">'+lang.label('http')+'</label><input id="protocol_socks5" type="radio" name="protocol"> <label for="protocol_socks5">'+lang.label('socks5')+'</label></td>',
            '                       </tr>',
            '                       <tr>',
            '                           <td></td>',
            '                           <td>'+lang.label('cloud_url')+':</td>',
            '                           <td><input type="text" id="proxy_server" maxlength="255"></td>',
            '                       </tr>',
            '                       <tr>',
            '                           <td></td>',
            '                           <td>'+lang.label('port')+'</td>',
            '                           <td><input type="text" id="proxy_port" maxlength="5"></td>',
            '                       </tr>',
            '                       <tr>',
            '                           <td></td>',
            '                           <td colspan="2" class="separate"></td>',
            '                       </tr>',
            '                       <tr>',
            '                           <td></td>',
            '                           <td>'+lang.label('proxy_authentication')+'</td>',
            '                           <td></td>',
            '                       </tr>',
            '                       <tr>',
            '                           <td></td>',
            '                           <td>'+lang.label('user_id')+':</td>',
            '                           <td><input type="text" id="proxy_user" maxlength="32"></td>',
            '                       </tr>',
            '                       <tr>',
            '                           <td></td>',
            '                           <td>'+lang.label('password')+':</td>',
            '                           <td><input type="password" id="proxy_password" maxlength="32"></td>',
            '                       </tr>',
            '                       <tr>',
            '                           <td></td>',
            '                           <td></td>',
            '                           <td class="clearfix"><div class="ui-button clearfix apply" id="serv_list_save"><div class="left"></div><div class="mid">'+lang.label('save_reload')+'</div></div><div class="ui-button clearfix cancel" id="serv_list_cancel"><div class="left"></div><div class="mid">'+lang.label('btn_cancel')+'</div></div></td>',
            '                       </tr>',
            '                   </tbody>',
            '               </table>',
            '           </div>',
            '       </div>',
            '   </div>',
            '   <div class="bd clearfix">',
            '       <div class="ui-button clearfix close" id="dialog_cancel"><div class="left"></div><div class="mid">'+lang.label('close')+'</div></div>',
            '   </div>',
            '</div>'
        ].join('');
        $$('#modalServerList .modalContent').set('html',HTML);
        $('checkAll').disabled = true;
        $$('#modalServerList .modalContent .proxyserver .title').addEvents({
            'mouseover': function(){
                this.addClass('hover');
            },
            'mouseout': function(){
                this.removeClass('hover');
            }
        });
        WF.util.Button();
        this.updateNotesLocation();
        this.getServerData();
        $('checkAll').addEvent('click', this.checkAll.bind(this));
        $('serv_list_cancel').addEvent('click', this.cancelProxy.bind(this));
        $('serv_list_save').addEvent('click', this.sendData.bind(this));
        $('enable_proxy').addEvent('click', this.controlElements.bind(this));
        $('dialog_cancel').addEvent('click', this.dialogcanel.bind(this));
        $('proxy_toggle').addEvent('click', function (e) {
            if (e && e.preventDefault){
                e.preventDefault();
            }
            if (this.msg){
                this.msg.clear();
            }
            $('proxy_content').setStyle('display', $('proxy_content').getStyle('display') == 'none' ? 'block' : 'none');
            this.showhideEditDelete($('proxy_content').getStyle('display') == 'none' ? false : true, false);
            $('proxy_toggle').className = $('proxy_toggle').className == 'off' ? 'on' : 'off';
        }.bind(this));
        this.adding = false;
        /*
        if (this.proxyDefaultOpened && $('proxy_toggle').className == 'btn_show') {
            //this.proxyDefaultOpened = false;
            $('proxy_toggle').fireEvent('click');
        }
        */

        var proxyPassword = $('proxy_password');
        proxyPassword.addEvent('focus',function(event){
            if (proxyPassword.get('passwordChanged') != 'true'){
                proxyPassword.set('value', '');
                proxyPassword.set('passwordChanged', 'true');
            }
        });
    },
    clearServerListOnClose: function(){
        if (this.dialogcanel){
            this.dialogcanel();
        }
        var dClose = $('modal_close');
        if (dClose){
            dClose.removeEvent('click',this.clearServerListOnClose);
        }
    },

    refreshServerNote:function(){
      var refreshServerModal=new WFModal({title:"",content:lang.labelText("refreshservernote"),width:300,height:330}, this);
    },

    delServerNote:function(){
      var delServerModal=new WFModal({title:"",content:lang.labelText("delservernote"),width:300,height:330}, this);
    },

    checkAll:function(){
            var do_check=$('checkAll').checked;
            $$('input.server_list').each(function(el){
                if(el.checked!==do_check)
                {
                    el.checked=do_check;
                    if(el.checked)
                    {
                        if(!this.objSelectedServerHash.has(el.value))
                        {
                            this.objSelectedServerHash.set(el.value,el.value);
                        }
                    }
                    else
                    {
                        if(this.objSelectedServerHash.has(el.value))
                        {
                            this.objSelectedServerHash.erase(el.value);
                        }
                    }
              }
            }.bind(this));
    },
    dialogcanel: function () {
        if (this.serverlistcheckarray) {
            this.serverlistcheckarray.cancel();
            this.serverlistcheckarray = null;
        }
        $each(this.scanservercheckarray, function (item, key) {
            item.cancel();
        }.bind(this));
        this.scanservercheckarray = {};
        if (this.proxylistcheckarray) {
            this.proxylistcheckarray.cancel();
            this.proxylistcheckarray = null;
        }
        this.objSelectedServerHash.empty();
        this.severlistModal.close();
    },

    cancelProxy: function (proxyDefaultOpened) {
        if ((typeof proxyDefaultOpened) != "boolean") {
            proxyDefaultOpened = false;
        }
        if (this.proxylistcheckarray) {
            this.proxylistcheckarray.cancel();
            this.proxylistcheckarray = null;
        }
        this.proxyDefaultOpened = proxyDefaultOpened;
        var myJSON = new WFRequest.JSON({
            url: homeBase + "inc/proxy_list.php?" + AddUrlParam(),
            method: 'post',
            data: JSON.encode({
                "act": "getall"
            }),
            urlEncoded: false,
            headers: {
                "Content-type": "application/json"
            },
            //onSuccess: function(jsonObj){ this.getProxySetting(jsonObj); }.bind(this)
            onSuccess: this.getProxySetting.bind(this)
        });
        myJSON.addEvent('onFailure', this.ajaxFailed);
        myJSON.send();
        this.proxylistcheckarray = myJSON;
        $('proxy_password').set('passwordChanged', 'false');
    },

    controlElements: function () {
        var isUsingProxy = $('enable_proxy').checked;
        $('protocol_http').disabled =
        $('protocol_socks5').disabled =
        $('proxy_server').disabled =
        $('proxy_port').disabled =
        $('proxy_user').disabled =
        $('proxy_password').disabled = !isUsingProxy;
    },

    getServerData: function () {
        if (this.serverlistcheckarray) {
            this.serverlistcheckarray.cancel();
            this.serverlistcheckarray = null;
        }
        var myJSON = new WFRequest.JSON({
            url: homeBase + "inc/server_list.php?" + AddUrlParam(),
            method: 'post',
            data: JSON.encode({
                "act": "getall"
            }),
            urlEncoded: false,
            headers: {
                "Content-type": "application/json"
            },
            //onSuccess: function(jsonObj){ this.makeContent(jsonObj); }.bind(this)
            onSuccess: this.makeContent.bind(this)
        });
        myJSON.addEvent('onFailure', this.ajaxFailed);
        myJSON.send();
        this.serverlistcheckarray = myJSON;
    },

    //event of clicking Save
    sendData: function () {
        if ($('serv_list_save').hasClass('disable')){
            return;
        }
        $('serv_list_save').addClass('disable');

        if (this.msg){
            this.msg.clear();
        }
        var proxy_enable = 0;
        var proxy_protocol = "http";
        var proxy_host = "";
        var proxy_port = 0;
        var proxy_auth = 0;
        var proxy_username = "";
        var proxy_password = "";

        $each(this.scanservercheckarray, function (item, key) {
            item.cancel();
        }.bind(this));
        this.scanservercheckarray = {};
        if ($('enable_proxy').checked) {
            if (!isValidHost($('proxy_server').value)) {
                this.showMsg(lang.label('proxy_server_invalid'));
                $('serv_list_save').removeClass('disable');
                return;
            }

            if (!isValidPort($('proxy_port').value)) {
                $('proxy_port').select();
                $('proxy_port').focus();
                this.showMsg(lang.label('proxy_port_invalid'));
                $('serv_list_save').removeClass('disable');
                return;
            }

            if ($('proxy_user').get('value').length === 0 && $('proxy_password').get('value').length > 0) {
                this.showMsg(lang.label('proxy_auth_invalid'));
                $('serv_list_save').removeClass('disable');
                return;
            }
            proxy_enable = 1;
        }
        else {
            proxy_enable = 0;
        }


        $('serv_list_save').disabled = true;

        if ($('protocol_http').checked) {
            proxy_protocol = "http";
            if ($('proxy_user').value.length > 0 || $('proxy_password').value.length > 0) {
                proxy_auth = 1;
            }
            else {
                proxy_auth = 0;
            }
        }
        else if ($('proxy_user').value.length > 0 || $('proxy_password').value.length > 0) {
            proxy_protocol = "sock5";
            proxy_auth = 1;
        }
        else {
            proxy_protocol = "sock5";
            proxy_auth = 0;
        }

        proxy_host = $('proxy_server').value;
        proxy_port = $('proxy_port').value;
        proxy_username = $('proxy_user').value;
        proxy_password = $('proxy_password').value;
        var proxyPasswordChanged = $('proxy_password').get('passwordChanged');

        var proxyobject = {};


        var data_info;
        if (this.firstproxyid) {
            if(proxyPasswordChanged == 'true'){
                proxyobject = {
                    "act": "update",
                    "proxyid": this.firstproxyid,
                    "name": "",
                    "proxyinfo": {
                        "host": proxy_host,
                        "port": parseInt(proxy_port,10),
                        "type": proxy_protocol,
                        "auth": proxy_auth,
                        "username": proxy_username,
                        "password": proxy_password,
                        "enable": proxy_enable
                    }
                };
            }else{
                proxyobject = {
                    "act": "update",
                    "proxyid": this.firstproxyid,
                    "name": "",
                    "proxyinfo": {
                        "host": proxy_host,
                        "port": parseInt(proxy_port,10),
                        "type": proxy_protocol,
                        "auth": proxy_auth,
                        "username": proxy_username,
                        "enable": proxy_enable
                    }
                };
            }
        }
        else {
            //data_info= 'act=add'+'&name=""&proxyinfo='+JSON.encode(proxyobject);
            proxyobject = {
                "act": "add",
                "name": "",
                "proxyinfo": {
                    "host": proxy_host,
                    "port": parseInt(proxy_port,10),
                    "type": proxy_protocol,
                    "auth": proxy_auth,
                    "username": proxy_username,
                    "password": proxy_password,
                    "enable": proxy_enable
                }
            };
        }

        data_info = JSON.encode(proxyobject);
        // sending data
        var myJSON = new WFRequest.JSON({
            url: homeBase + "inc/proxy_list.php?" + AddUrlParam(),
            method: 'post',
            data: data_info,
            urlEncoded: false,
            headers: {
                "Content-type": "application/json"
            },
            //onSuccess: function(jsonObj){ this.setProxySetting(jsonObj); }.bind(this)
            onSuccess: this.setProxySetting.bind(this)
        });
        myJSON.addEvent('onFailure', this.ajaxFailed);
        myJSON.send();


    },

    //setProxySetting:function(jsonObj){
    setProxySetting: function (responseObj) {
        var jsonObj = responseObj[1];
        if (jsonObj.errcode !== 0) {
            var message = "";
            switch (jsonObj.errcode) {
            case 300:
            case 301:
            case 302:
            case 303:
            case 304:
            case 305:
            case 306:
                message += lang.label("errorcode_" + jsonObj.errcode);
                break;
            default:
                message += lang.label("errorcode_undefined");
            }
            //alert(lang.label('set_proxy_failed')+" ("+lang.label('error')+jsonObj.errcode+")");
            this.showMsg(lang.label('set_proxy_failed') + "<BR>" + message);
            this.cancelProxy(true);
            if ($('serv_list_save')){
                $('serv_list_save').removeClass('disable');
            }
            return;
        }

        if (!this.firstproxyid) {
            this.firstproxyid = jsonObj.result;
        }

        var data_info;

        if ($('enable_proxy').checked) {
            data_info = JSON.encode({
                "enable": 1,
                "proxyid": this.firstproxyid
            });
        }
        else {
            data_info = JSON.encode({
                "enable": 0
            });
        }
        var myJSON = new WFRequest.JSON({
            url: homeBase + "inc/proxy_enable.php?" + AddUrlParam(),
            method: 'post',
            data: data_info,
            urlEncoded: false,
            headers: {
                "Content-type": "application/json"
            },
            //onSuccess: function(jsonObj){ this.enableordisableProxy(jsonObj,null,true); }.bind(this)
            uid: null,
            needRefresh: true,
            onSuccess: this.enableordisableProxy.bind(this)
        });
        myJSON.addEvent('onFailure', this.ajaxFailed);
        myJSON.send();
    },


    //enableordisableProxy:function(jsonObj,uid,needRefresh){
    enableordisableProxy: function (responseObj) {
        jsonObj = responseObj[1];
        uid = responseObj[2].options.uid;
        needRefresh = responseObj[2].options.needRefresh;
        if (jsonObj.errcode !== 0) {
            var message = "";
            switch (jsonObj.errcode) {
            case 500:
            case 501:
            case 502:
            case 503:
            case 504:
                message += lang.label("errorcode_" + jsonObj.errcode);
                break;
            default:
                message += lang.label("errorcode_undefined");
            }
            //alert(lang.label('proxy_enable_failed')+" ("+lang.label('error')+jsonObj.errcode+")");
            this.showMsg(lang.label('proxy_enable_failed') + "<BR>" + message);
            if($('serv_list_save')){
                $('serv_list_save').removeClass('disable');
            }
            return;
        }

        if (needRefresh) {
            this.proxyDefaultOpened = true;
            this.onFinish();
        }

        //this.closeModal();
    },

    fillLastUpdate: function () {
        if ($('updateText') === null) {
            return;
        }
        this.updateText = $('updateText').setHTML(lang.label('last_check') + new Date().formatDate(lang.label('dateformat')));
        /*
        new Element('img', {
            'events': {
                'click': this.refresh.bind(this)
            },
            'class': 'refresh_server',
            'title': lang.labelText('refresh'),
            'src': this.refresh_icon,
            'style': 'display:' + (($('proxy_toggle').className == 'btn_hide') ? 'none' : 'inline-block')
        }).injectInside($('updateText'));
        */
    },
    // event of refresh icon
    refresh: function (e) {
        e.preventDefault();
        if (this.msg){
            this.msg.clear();
        }
        // window.location.reload();
        if (this.serverlistcheckarray) {
            this.serverlistcheckarray.cancel();
            this.serverlistcheckarray = null;
        }
        $each(this.scanservercheckarray, function (item, key) {
            item.cancel();
        }.bind(this));
        this.scanservercheckarray = {};
        if (this.proxylistcheckarray) {
            this.proxylistcheckarray.cancel();
            this.proxylistcheckarray = null;
        }
        this.lost_connection = [];
        this.timeout_connection = [];
        this.proxyDefaultOpened = null;
        this.objSelectedServerHash.empty();
        this.onFinish();
    },
    //makeContent: function(jsonObj){
    makeContent: function (responseObj) {
        var jsonObj = responseObj[1];
        if (!$chk(jsonObj)) {
            return;
        }
        if (jsonObj.errcode !== 0) {
            var message = "";
            switch (jsonObj.errcode) {
            case 200:
            case 201:
            case 202:
            case 203:
            case 204:
            case 205:
            case 206:
                message += lang.label("errorcode_" + jsonObj.errcode);
                break;
            default:
                message += lang.label("errorcode_undefined");
            }
            //alert(lang.label('get_serverlist_failed')+" ("+lang.label('error')+jsonObj.errcode+")");
            this.showMsg(lang.label('get_serverlist_failed') + "<BR>" + message);
            return;
        }
        //var table = $(this.table_id);
        var servers = jsonObj.result;
        if (this.supportServerTypes.length > 0 && servers.length > 0){
            var tmpServers = [];
            for (var i=0,j=this.supportServerTypes.length;i<j;++i){
                for (var x=0,y=servers.length;x<y;++x){
                    if (this.supportServerTypes[i] === servers[x].hostinfo.type){
                        tmpServers.push(servers[x]);
                    }
                }
            }
            servers = tmpServers;
        }
        g_serverlist.setServerList(servers);

        if (this.supportServerTypes.length > 0 && g_serverlist.serverlisttypearray.length > 0){
            var tmpServerListTypes = [];
            for (var i=0,j=this.supportServerTypes.length;i<j;++i){
                for (var x=0,y=g_serverlist.serverlisttypearray.length;x<y;++x){
                    if (this.supportServerTypes[i] === g_serverlist.serverlisttypearray[x].type){
                        tmpServerListTypes.push(g_serverlist.serverlisttypearray[x]);
                    }
                }
            }
            g_serverlist.serverlisttypearray = tmpServerListTypes;
        }

        g_serverlist.adjustLastCheckTimedifference();
        this.fillLastUpdate();
        /*
        if ($('add_server') === null) {
            return;
        }
        disable function
        $('add_server').set('value',lang.labelText('add_server')).set('disabled', ($('proxy_toggle').className == 'btn_hide') ? true : false);
        $('del_server').set('value',lang.labelText('del_server')).set('disabled', ($('proxy_toggle').className == 'btn_hide') ? true : false);
        $('refresh_server').set('value',lang.labelText('refresh')).set('disabled', ($('proxy_toggle').className == 'btn_hide') ? true : false);
        */
        this.scanservercheckarray = {};
        this.servData = {};
        if (servers.length > 0) {
            this.ajaxCount = servers.length; // how many ajax connections will be made
            this.currentCount = 0;
            // show all lost connection message in once
            var showSingle = false;
            // got probelms on $each in IE7 when iterable is from XML
            // using [for] here
            for (var index = 0; index < servers.length; index++) {
                var item = {
                    name: servers[index].name,
                    type: servers[index].hostinfo.type,
                    account: (servers[index].name == "localhost") ? "" : servers[index].hostinfo.username,
                    password: (servers[index].name == "localhost") ? "" : servers[index].hostinfo.password,
                    customFields: (servers[index].hostinfo.customFields) ? servers[index].hostinfo.customFields : null
                };
                this.makeRow(item, servers[index].id);
                this.checkStatus(servers[index].id, servers[index].hostinfo.type, showSingle, (index + 2) - servers.length);
            }
            //$('checkAll').disabled = false;
            this.severlistModal.onResize();
            this.waitingData();
        } else {
            this.isAjaxDone = true;
        }
        if (this.proxylistcheckarray) {
            this.proxylistcheckarray.cancel();
            this.proxylistcheckarray = null;
        }
        var myJSON = new WFRequest.JSON({
            url: homeBase + "inc/proxy_list.php?" + AddUrlParam(),
            method: 'post',
            data: JSON.encode({
                "act": "getall"
            }),
            urlEncoded: false,
            headers: {
                "Content-type": "application/json"
            },
            //onSuccess: function(jsonObj){ this.getProxySetting(jsonObj); }.bind(this)
            onSuccess: this.getProxySetting.bind(this)
        });
        myJSON.addEvent('onFailure', this.ajaxFailed);
        myJSON.send();
        this.proxylistcheckarray = myJSON;

    },

    getProxySetting: function (responseObj) {
	        jsonObj = responseObj[1];
	        //it means user close dialog
	        if (!$chk(jsonObj)) {
                if ($('serv_list_save')){
                    $('serv_list_save').removeClass('disable');
                }                
	            return;
	        }
	        // fill proxy setting
	        if (jsonObj.errcode !== 0) {
	            var message = "";
	            switch (jsonObj.errcode) {
	            case 300:
	            case 301:
	            case 302:
	            case 303:
	            case 304:
	            case 305:
	            case 306:
	                message += lang.label("errorcode_" + jsonObj.errcode);
	                break;
	            default:
	                message += lang.label("errorcode_undefined");
	            }
	            //alert(lang.label('get_proxylist_failed')+" ("+lang.label('error')+jsonObj.errcode+")");
	            this.showMsg(lang.label('get_proxylist_failed') + "<BR>" + message);
                if ($('serv_list_save')){
                    $('serv_list_save').removeClass('disable');
                }
	            return;
	        }

	        if (jsonObj.result.length === 0) {
	        	if($('enable_proxy') === null){
                    if ($('serv_list_save')){
                        $('serv_list_save').removeClass('disable');
                    }
	        		return;
	        	}
	            $('enable_proxy').checked = false;
	            $('protocol_http').checked = true;
	            $('proxy_server').value = "";
	            $('proxy_port').value = "";
	            $('proxy_user').value = "";
	            $('proxy_password').value = "";

	        }
	        else {

	            this.firstproxyid = jsonObj.result[0].id;
	            $('enable_proxy').checked = (jsonObj.result[0].hostinfo.enable == 1) ? true : false;
	            if (jsonObj.result[0].hostinfo.type == "http") {
	                $('protocol_http').checked = true;
	            }
	            else {
	                $('protocol_socks5').checked = true;
	            }
	            $('proxy_server').value = jsonObj.result[0].hostinfo.host;
	            $('proxy_port').value = (jsonObj.result[0].hostinfo.port) ? jsonObj.result[0].hostinfo.port : "";
	            $('proxy_user').value = jsonObj.result[0].hostinfo.username;
                $('proxy_password').value = jsonObj.result[0].hostinfo.password;
	        }
	        this.controlElements();
	        $('enable_proxy').disabled = false;
	        /*
	        $('serv_list_save').disabled = false;
	        $('serv_list_cancel').disabled = false;
	        */
                $('add_server').removeEvents('click');
	        $('add_server').addEvent('click', this.addServer.bind(this));
                $('del_server').removeEvents('click');
	        $('del_server').addEvent('click', this.delServer.bind(this));
	        $('refresh_server').removeEvents('click');
            $('refresh_server').addEvent('click', this.refresh.bind(this));

	        // is canceling/closing proxy setitng
	        if (this.proxyDefaultOpened === false && $('proxy_toggle').className == 'on') {
	            this.proxyDefaultOpened = null;
	            //$('messageBox').setHTML('').className = null;
	            $('proxy_toggle').fireEvent('click');
	        }
    },

    delServer:function(e){
        e.preventDefault();
        if (!this.isAjaxDone || $('enable_proxy').disabled === true) {
            return;
        }
        if(this.objSelectedServerHash.getLength()===0)
        {
            this.showMsg(lang.label('at_least_one_server'));
            return;
        }
        if (!confirm(lang.labelText('confirm_delete'))) {
            return;
        }
        if (this.msg){
            this.msg.clear();
        }
        var strIDlist=this.objSelectedServerHash.getKeys().join(",");
        // sent deleting data to server
        var myJSON = new WFRequest.JSON({
            url: homeBase + "inc/server_list.php?" + AddUrlParam(),
            method: 'post',
            parameter: strIDlist,
            data: JSON.encode({
                "act": "batchdelete",
                "serverids":strIDlist
            }),
            urlEncoded: false,
            headers: {
                "Content-type": "application/json"
            },
            onSuccess: this.deleteServerResponse.bind(this)
        });
        myJSON.addEvent('onFailure', this.ajaxFailed);
        myJSON.send();
    },

    updatecheckAllBox:function(){
        var finalresult=true;
        $$('input.server_list').each(function(el){
            finalresult=finalresult&el.checked;
        });
        $('checkAll').checked=finalresult;
    },

    updateSelectedServer:function(e){
        var event = new Event(e);
        if(event.target.checked)
        {
            if(!this.objSelectedServerHash.has(event.target.value))
            {
                this.objSelectedServerHash.set(event.target.value,event.target.value);
            }
        }
        else
        {
            if(this.objSelectedServerHash.has(event.target.value))
            {
                this.objSelectedServerHash.erase(event.target.value);
            }
        }
        this.updatecheckAllBox();
    },
    makeRow: function (item, uid) { //item = {name:'name',account:'account',password:'password'}
	        var table = $(this.table_id);
	        if(table === null){
	        	return;
	        }
	        var row = table.insertRow(table.rows.length);
	        var index = row.rowIndex;
	        if (index % 2 === 0) {
	            $(row).addClass('even');
	        }
	        row.setAttribute('id', uid);
	        this.servData[uid] = item;
	        var td_0 = new Element('td').injectInside(row);
	        if(item.name !== 'localhost')
	        {
	          td_0.setHTML('<input type="checkbox" class="server_list" disabled=true value="'+uid+'">');
	          td_0.getElement('input').addEvent('click',this.updateSelectedServer.bind(this));
	        }

            var ipTip = changeLineForTip(item.name, 70);
	        var td_1 = new Element('td', {'html':this.status_img+'<div class="ip ellipsis" title="'+ipTip+'">'+item.name+'</div>'}).injectInside(row);
            td_1.addClass('addrcol');
            if (this.showServerTypeColumn === true){
                var td_2 = new Element('td',{'html':'<span title="'+lang.label(item.type)+'">'+lang.label(item.type)+'</span>'}).injectInside(row);
            }
	        /*var td_1 = new Element('td', {
	            'style': 'text-align:center;'
	        }).setHTML("<table><tr><td style='border-left:0px' width='5%'>" + this.status_img + "</td><td style='border-left:0px' width='95%'><div class='ServerNameorIPWrap' title='" + item.name + "' style='width:350px'>" + item.name + "</div></td></tr></table>").injectInside(row);
	        */
	        /*var td_2 = new Element('td', {
	            'class': 'connection_status'
	        }).setHTML(lang.label("connection_testing")).injectInside(row);*/
	        /*var td_4 = new Element('td').injectInside(row);*/

	        /*
	        var td_2 = new Element('td',{
	            'style': 'text-align:left;'
	        }).setHTML("<div class='ServerNameorIPWrap' title='" + lang.label(item.type) + "' style='width:300px'>" + lang.label(item.type) + "</div>").injectInside(row);
	        */
	        var td_3 = new Element('td').injectInside(row);
	        if (item.name != "localhost" && uid != "1") {
	            var edit_link = new Element('a', {
	                'events': {
	                    'click': this.editServer.bind(this)
	                },
	                'href': '#',
	                'class': 'edit',
	                'title': lang.labelText('edit'),
	                'style': 'display:' + (($('proxy_toggle').className == 'on') ? 'none' : 'block')
	            }).injectInside(td_3);
	            /*
	            var delete_link = new Element('a', {
	                'events': {
	                    'click': function (e) {
	                        this.deleteServer(e);
	                    }.bind(this)
	                },
	                //'href': 'javascript:void(0);',
	                'class': 'delete_icon',
	                'title': lang.labelText('delete'),
	                'style': 'display:' + (($('proxy_toggle').className == 'btn_hide') ? 'none' : 'block')
	            }).injectInside(td_4);
	            */
	        } else {
	            td_3.setHTML('&nbsp;');
	            if (custom_options.hide_localhost) {
	                $(row).setStyle("display", "none");
	            }
	        }
    },

    // check the connecttion status of a server
    checkStatus: function (uid, type, showSingle, showAll) {
        var myJSON = new WFRequest.JSON({
            url: homeBase + proxyHandler + "?" + AddUrlParam() + "&act=check&module=" + type + "&serverid=" + uid,
            timeout: ajaxTimeoutValue,
            //onTimeout: function() {this.onTimeOut(uid);}.bind(this),
            //onSuccess: function(jsonObj){this.changeStatus(jsonObj,uid,showSingle,showAll||false); }.bind(this)
            uid: uid,
            showsingle: showSingle,
            showall: showAll || false,
            onFailure: this.onFailure.bind(this),
            onSuccess: this.changeStatus.bind(this)
        });
        $('checkAll').disabled = true;
        myJSON.send();
        this.scanservercheckarray[uid] = myJSON;
    },
    onFailure: function (reqObj) {
        $('checkAll').disabled = false;
        if (reqObj.isTimeout === true) {
            this.onTimeOut.bind(this)(reqObj);
            return;
        }
        var uid = reqObj.options.uid;

        if($(uid) === null){
            return;
        }
        var dCheckbox = $(uid).getElement('input.server_list');
        if (dCheckbox){
            dCheckbox.disabled = false;
        }

        var img = $(uid).getElementsByTagName('img')[0];
        var connection_status = $(uid).getElement("td.connection_status");
        //$(connection_status).setHTML(lang.label("failed"));
        var status = 'offline';
        img.src = homeBase + 'img/default/server_' + status + '_16.gif';
        img.title = lang.labelText(status);
        this.lost_connection.push(uid);
        $(uid).addClass('lost_connection');
        this.currentCount++; // means it's done
        if (this.currentCount == this.ajaxCount) {
            this.isAjaxDone = true;
        }
    },
    //onTimeOut:function(uid){
    onTimeOut: function (reqObj) {
        var uid = reqObj.options.uid;
        var dCheckbox = $(uid).getElement('input.server_list');
        if (dCheckbox){
            dCheckbox.disabled = false;
        }
        if ($('updateText').getProperty('save_click') == 'true') {
            this.showMsg(lang.label('timeout_connect') + ' ' + $(uid).getElement("div.ip").get('text'));
            $('updateText').setProperty('save_click', 'false');
        }
        var img = $(uid).getElementsByTagName('img')[0];
        var connection_status = $(uid).getElement("td.connection_status");
        //$(connection_status).setHTML(lang.label("timeout"));
        var status = 'offline';
        img.src = homeBase + 'img/default/server_' + status + '_16.gif';
        img.title = lang.labelText(status);
        this.timeout_connection.push(uid);
        $(uid).addClass('lost_connection');
        this.currentCount++; // means it's done
        if (this.currentCount == this.ajaxCount) {
            this.isAjaxDone = true;
        }
    },
    // called on-complete of checkStatus, change the status icon and makeing the message box
    //changeStatus: function(jsonObj, uid, showSingle, showAll){
    changeStatus: function (reqObj) {
        var jsonObj = reqObj[1];
        var uid = reqObj[2].options.uid;
        var showSingle = reqObj[2].options.showsingle;
        var showAll = reqObj[2].options.showall;

        if (!$chk(jsonObj) || $(uid) === null) {
            return;
        }
        var dCheckbox = $(uid).getElement('input.server_list');
        if (dCheckbox){
            dCheckbox.disabled = false;
        }

        var img = $(uid).getElementsByTagName('img')[0];
        //var connection_status = $(uid).getElement("td.connection_status");
        var status = jsonObj.errcode === 0 ? 'online' : 'offline';
        if(img)
        {
            img.src = homeBase + 'img/default/server_' + status + '_16.gif';
            img.title = lang.labelText(status);
        }
        if (status == 'offline') {
            if (jsonObj.errcode == 423) {
                this.timeout_connection.push(uid);
                //$(connection_status).setHTML(lang.label("timeout"));
            }
            else {
                this.lost_connection.push(uid);
                //$(connection_status).setHTML(lang.label("failed"));
            }
            $(uid).addClass('lost_connection');
            g_serverlist.updateLastCheck(uid, 0);
        } else {
            $(uid).removeClass('lost_connection');
            //$(connection_status).setHTML(lang.label("success"));
            g_serverlist.updateLastCheck(uid, new Date().getTime());
        }

        if (showSingle) {
            /*
            this.showMsg(
            status == 'offline' ? // message content
            lang.label('failed_connect') + this.servData[uid].name.wordWrap(serverwrapcharscount, "<BR>") : lang.label('add_sucessful_1') + this.servData[uid].name.wordWrap(serverwrapcharscount, "<BR>") + lang.label('add_sucessful_2'), status == 'offline' ? 'error' : 'notice' // message type
            );*/
        }

        this.currentCount++; // means it's done
        if (this.currentCount == this.ajaxCount) {
            $('checkAll').disabled = false;
            this.isAjaxDone = true;
        }
    },

    // Event of Add Server button
    addServer: function (e) {
        if (!this.isAjaxDone || $('enable_proxy').disabled === true) {
            return;
        }
        this.editServer(e,'add_server');
        $(this.table_id).addClass('adding');
        this.adding = true;
    },

    // Event of edit button, this function will be share with event of Adding button
    editServer: function (e, add_server) {
        e.preventDefault();
        if (this.msg){
            this.msg.clear();
        }
        if (!this.isAjaxDone || $('enable_proxy').disabled === true) {
            return;
        }
        // hide add server button when add/edit server
        if (this.adding) {
            return;
        }
        var sName,account,password;
        if(add_server){
            var uid = '';
        }
        else{
            var uid = e.target.parentNode.parentNode.id;
        }
        if (uid !== '') { // editing a server
            $(uid).style.display = 'none';
            sName = this.servData[uid].name;
            account = this.servData[uid].account;
            password = ($defined(this.servData[uid].password) && this.servData[uid].password)?'*****':'';
        } else { // adding a new server
            sName = '';
            account = '';
            password = '';
        }
        var serverlisttype = g_serverlist.getServerListType();
        var type_option = '';
        var allCustomFields = '';
        var defaultPasswordFields = [];  // password customFields that have default value when adding new server or changing server type
        $each(serverlisttype, function (item, index){
            type_option += '<option value="'+item.type+'" title="'+lang.labelText(item.type)+'"'+((uid!==''&&this.servData[uid].type===item.type)?' selected':'')+'>'+lang.labelText(item.type)+'</option>';
            if (item.customFields){
                var rows = JSON.decode(item.customFields, true);
                allCustomFields += '<div id="' + item.type + '-fields">';
                for (var i=0,j=rows.length;i<j;++i){
                    allCustomFields += '<div><span>' + lang.labelText(rows[i].caption) + '</span><input';
                    for (var prop in rows[i]){
                        if (prop === 'caption'){
                            continue;
                        }
                        allCustomFields += ' ' + prop + '="';
                        if (prop === 'value'){
                            if (rows[i].type !== 'password'){
                                if (uid !== '' && this.servData[uid].type === item.type){
                                    if (this.servData[uid].customFields && typeof this.servData[uid].customFields[rows[i].name] !== 'undefined'){
                                        allCustomFields += this.servData[uid].customFields[rows[i].name];
                                    }
                                } else if (rows[i][prop] !== ''){
                                    allCustomFields += lang.labelText(rows[i][prop]);
                                }
                            }else{
                                if(uid !== '' && this.servData[uid].type === item.type){
                                    //show value of password customFields when editing server
                                    if (this.servData[uid].customFields && typeof this.servData[uid].customFields[rows[i].type] !== 'undefined'){
                                        if (this.servData[uid].customFields[rows[i].type][rows[i].name]){
                                            //if  password customField has value
                                            this.servData[uid].customFields[rows[i].type][rows[i].name] = '*****';
                                        }else{
                                            //if  password customField does not have value
                                            this.servData[uid].customFields[rows[i].type][rows[i].name] = '';
                                        }
                                        allCustomFields += this.servData[uid].customFields[rows[i].type][rows[i].name];
                                    }
                                }else{
                                    if (rows[i].value){
                                        //save password customField that has default value for all server type when adding new server or edting server(using by changing server type)
                                        defaultPasswordFields.push('#'+item.type + '-fields input[name='+ rows[i].name+']');
                                    }
                                    allCustomFields += rows[i].value;
                                }
                            }
                        } else {
                            allCustomFields += rows[i][prop];
                        }
                        allCustomFields += '"';
                    }
                    allCustomFields += '></div>';
                }
                allCustomFields += '</div>';
            }
        }.bind(this));
        var HTML =[
            '           <table>',
            '               <tbody>',
            '                   <tr>',
            '                       <td>'+lang.label('server_name')+':</td>',
            '                       <td><input type="text" id="server_name" name="server_name" class="server_name text" maxlength="255" value="' + sName + '"></td>',
            '                   </tr>',
            '                   <tr>',
            '                       <td></td>',
            '                       <td><span class="example">'+lang.label('server_example')+'</span></td>',
            '                   </tr>',
            '                   <tr>',
            '                       <td>'+lang.label('type')+':</td>',
            '                       <td><select id="server_type" name="server_type">'+type_option+'</select></td>',
            '                   </tr>',
            '                   <tr>',
            '                       <td>'+lang.label('account')+':</td>',
            '                       <td><input type="text" id="account_text" class="account_text" name="account" maxlength="32" value="' + account.replace(/"/g, '&quot;') + '"></td>',
            '                   </tr>',
            '                   <tr>',
            '                       <td>'+lang.label('password')+':</td>',
            '                       <td><input id="password" type="password" class="password text" name="password" maxlength="32" value="' + password.replace(/"/g, '&quot;') + '"></td>',
            '                   </tr>',
            '                   <tr>',
            '                       <td id="displayblock" colspan="2"></td>',
            '                   </tr>',
            '                   <tr>',
            '                       <td></td>',
            '                       <td class="cleafix"><div class="ui-button clearfix save" id="update_or_add_save_button"><div class="left"></div><div class="mid">'+lang.label('btn_save')+'</div></div><div class="ui-button clearfix cancel" id="update_or_add_cancel_button"><div class="left"></div><div class="mid">'+lang.label('btn_cancel')+'</div></div></td>',
            '                   </tr>',
            '               </tbody>',
            '           </table>',
        ].join('');

        if (allCustomFields !== ''){
            HTML += '<div id="hiddenblock">' + allCustomFields + '</div>';
        }
        $$('#serverlist_setting .addserver').set('html',HTML);
        $$('#serverlist_setting .addserver').set('styles',{'display':'block'});
        this.severlistModal.onResize();
        //bind event
        WF.util.Button();

        defaultPasswordFields.each(function(item,i){
            $$(item)[0].set('defaultPassword', 'true');
        });
        var passwords = $$('#serverlist_setting .addserver input[type=password]');
        passwords.each(function(item,i){
            item.addEvent('focus',function(event){
                if (item.get('passwordChanged') != 'true'){
                    item.set('value', '');
                    item.set('passwordChanged', 'true');
                    item.set('defaultPassword', 'false');
                }
            });
        });
        var displayblock = $('displayblock');
        var hiddenblock = $('hiddenblock');
        var that = this;
        $('server_type').addEvent('change', function (event) {
            var showFields = displayblock.getElement('div');
            var selFields = $(this.value + '-fields');
            if (showFields){
                showFields.inject(hiddenblock);
            }
            if (selFields){
                selFields.inject(displayblock);
            }
            if (uid){
                //set  passwordChanged to be true when changing server type and the password customField is empty
                if (that.servData[uid].type != this.value){
                    var passwordFields = $$('#'+this.value + '-fields'+' input[type=password]');
                    passwordFields.each(function(item,i){
                        if($$(item)[0].get('value') === ''){
                            $$(item)[0].set('passwordChanged', 'true');
                        }
                    });
                }
            }

            if (g_serverlist.isPasswordOnly(this.value)) {
                $$('#serverlist_setting .addserver .account_text').set('disabled', true);
            }
            else {
                $$('#serverlist_setting .addserver .account_text').set('disabled', false);
            }
        });
        $('server_type').addEvent('keyup',function(e){
            if (e.key === 'down' || e.key === 'up'){
                e.target.fireEvent('change');
            }
        });
        $('server_type').fireEvent('change');

        if (uid !== '') {
            $('server_type').set('value', this.servData[uid].type);
            $('server_type').set('title', lang.labelText(this.servData[uid].type));
            if (g_serverlist.isPasswordOnly(this.servData[uid].type)) {
                $$('#serverlist_setting .addserver .account_text').set('disabled', true);
            }
            else {
                $$('#serverlist_setting .addserver .account_text').set('disabled', false);
            }
        }
        $('update_or_add_save_button').addEvent('click',function(){
            if ($('update_or_add_save_button').hasClass('disable')){
                return;
            }
            $('update_or_add_save_button').addClass('disable');
            this.saveServer(uid, $$('#serverlist_setting .addserver')[0]);
        }.bind(this));
        $('update_or_add_cancel_button').addEvent('click',function(){
            //$('messageBox').setHTML('').className = null;
            if (this.msg){
                this.msg.clear();
            }
            this.cancelServer(uid, $$('#serverlist_setting .addserver'));
            this.showhideEditDelete(false, true);
            this.updateNotesLocation();
        }.bind(this));
        //hide edit delete buttons
        this.showhideEditDelete(true, true);
        // set focus on server name
        $$('#serverlist_setting .server_name')[0].focus();
        $$('#serverlist_setting .server_name')[0].select();
    },
    showhideEditDelete: function (displayvalue, includeProxyToggle) {
        var strDisplayValue = '';
        if(false === displayvalue) {
            strDisplayValue = 'block';
        }
        else {
            strDisplayValue = 'none';
        }
        $('proxy_toggle').setStyle('display', strDisplayValue);
        $('add_server').set('styles',{'display': strDisplayValue});
        $('del_server').set('styles',{'display': strDisplayValue});
        $('refresh_server').set('styles',{'display': strDisplayValue});
        $$('#serverlist_setting .serverlist a.edit').setStyle("display", strDisplayValue);
        this.severlistModal.onResize();
    },


    // save the setting of edit
    saveServer: function (uid, tr) {
        if (this.msg){
            this.msg.clear();
        }
        $('updateText').setProperty('save_click', 'true');
        // data validation
        var url = trimString(tr.getElementsByTagName('input')[0].value.toLowerCase());

        var objUrlProcessor = new WFUrlProcessor(url);
        if (!objUrlProcessor.isValid()) {
            tr.getElementsByTagName('input')[0].select();
            tr.getElementsByTagName('input')[0].focus();
            this.showMsg(lang.label('url_invalid'));
            $('update_or_add_save_button').removeClass('disable');
            return;
        }

        var UriObj = objUrlProcessor.objUrl;
        if ((UriObj.path.length > 0 && UriObj.path !== "/") || (UriObj.protocol.toLowerCase() !== "http" && UriObj.protocol.toLowerCase() !== "https")) {
            this.showMsg(lang.label('url_invalid'));
            $('update_or_add_save_button').removeClass('disable');
            return;
        }

        if (UriObj.port === "") {
            if (UriObj.protocol.toLowerCase() ==="http") {
                UriObj.port = 80;
            }
            else {
                UriObj.port = 443;
            }
        }

        var samename = false;
        $each(this.servData, function (item, index) {
            if (item.name != "localhost"){
                var servDataUriObj = parseUrl(item.name);
                if (servDataUriObj.port === "") {
                    servDataUriObj.port = ((servDataUriObj.protocol.toLowerCase() == "http") ? 80 : 443);
                }
                if (UriObj.source.toLowerCase() === servDataUriObj.source.toLowerCase()) {
                    if (!uid) {
                        this.showMsg(lang.label('duplicated_server'));
                        samename = true;
                    }
                    else {
                        if (parseInt(uid,10) != index) {
                            this.showMsg(lang.label('duplicated_server'));
                            samename = true;
                        }
                    }
                }
            }
        }.bind(this));
        // UI change
        if (samename) {
            $('update_or_add_save_button').removeClass('disable');
            return;
        }

        // check customized fields
        var userInputs = $('displayblock').getElements('input');
        var defaultPasswordFields = '';    //save password customField which using default password
        if (userInputs.length > 0){
            var customFieldsObj = {};   //save customField for DB
            var customFieldsUIObj = {};    //save customField for UI
            for (var i=0,j=userInputs.length;i<j;++i){
                if (userInputs[i].getProperty('allowempty') == 0 && userInputs[i].value === ''){
                    this.showMsg(userInputs[i].getPrevious().firstChild.nodeValue + ':' + lang.label('empty_not_allow'));
                    $('update_or_add_save_button').removeClass('disable');
                    return;
                }

                if (userInputs[i].type === 'password'){
                    if (typeof customFieldsObj.password === 'undefined'){
                        customFieldsObj.password = {};
                        customFieldsUIObj.password= {};
                    }

                    if (userInputs[i].get('passwordChanged') == 'true'){
                        //save password customFields based on user input
                        customFieldsObj.password[userInputs[i].name] = userInputs[i].value;
                    }else{
                        if (userInputs[i].get('defaultPassword') == 'true'){
                            //save default password customFields which need to get default value from db
                            defaultPasswordFields += userInputs[i].name+',';
                            customFieldsObj.password[userInputs[i].name] = undefined;
                        }else{
                            if (uid) {
                                //password customField need to get original value from db when editing server
                                customFieldsObj.password[userInputs[i].name] = undefined;
                            }else{
                                //password customField need to be empty when adding server
                                customFieldsObj.password[userInputs[i].name] = '';
                            }
                        }
                    }

                    //prepare customField for UI
                    if (userInputs[i].value){
                        customFieldsUIObj.password[userInputs[i].name] = '*****';
                    }else{
                        customFieldsUIObj.password[userInputs[i].name] = '';
                    }
                } else {
                    customFieldsObj[userInputs[i].name] = userInputs[i].value;
                    customFieldsUIObj[userInputs[i].name] = userInputs[i].value;
                }
            }

            if (defaultPasswordFields){
                defaultPasswordFields = defaultPasswordFields.substring(0, defaultPasswordFields.length-1);
            }
        }

        /*
        $('messageBox').setStyles({
            'display': 'block',
            'height': 'auto',
            'backgroundColor': ''
        }).setHTML('').className = '';

        $('update_or_add_save_button').disabled = true;
        $('update_or_add_cancel_button').disabled = true;
        */
        var data_info;
        var serverinfo = {};
        var servertypeselectelment = tr.getElementsByTagName('select')[0];
        var serverPasswordChanged = tr.getElementsByTagName('input')[2].get('passwordChanged');
        // sync data in object
        if (uid) { //edit
            this.servData[uid].name= url;
            this.servData[uid].account=tr.getElementsByTagName('input')[1].value;
            this.servData[uid].password=tr.getElementsByTagName('input')[2].value;
            this.servData[uid].type=servertypeselectelment.options[servertypeselectelment.options.selectedIndex].value;

            if (serverPasswordChanged == 'true'){
                serverinfo = {
                    "act": "update",
                    "name": url,
                    "serverid": uid,
                    "defaultPasswordFields" : defaultPasswordFields,
                    "serverinfo": {
                        "host": UriObj.host.toLowerCase(),
                        "port": UriObj.port,
                        "protocol": UriObj.protocol.toLowerCase(),
                        "username": tr.getElementsByTagName('input')[1].value,
                        "password": tr.getElementsByTagName('input')[2].value,
                        "proxy_enable": ($('enable_proxy').checked) ? 1 : 0,
                        "proxy_id": this.firstproxyid,
                        "type": servertypeselectelment.options[servertypeselectelment.options.selectedIndex].value
                    }
                };
            }else{
                serverinfo = {
                    "act": "update",
                    "name": url,
                    "serverid": uid,
                    "defaultPasswordFields" : defaultPasswordFields,
                    "serverinfo": {
                        "host": UriObj.host.toLowerCase(),
                        "port": UriObj.port,
                        "protocol": UriObj.protocol.toLowerCase(),
                        "username": tr.getElementsByTagName('input')[1].value,
                        "proxy_enable": ($('enable_proxy').checked) ? 1 : 0,
                        "proxy_id": this.firstproxyid,
                        "type": servertypeselectelment.options[servertypeselectelment.options.selectedIndex].value
                    }
                };
            }
        } else { //add
            //data_info='act=add'+'&name='+tr.getElementsByTagName('input')[0].value+"&serverinfo="+JSON.encode(serverinfo);
            serverinfo = {
                "act": "add",
                "name": url,
                "defaultPasswordFields" : defaultPasswordFields,
                "serverinfo": {
                    "host": UriObj.host.toLowerCase(),
                    "port": UriObj.port,
                    "protocol": UriObj.protocol.toLowerCase(),
                    "username": tr.getElementsByTagName('input')[1].value,
                    "password": tr.getElementsByTagName('input')[2].value,
                    "proxy_enable": ($('enable_proxy').checked) ? 1 : 0,
                    "proxy_id": this.firstproxyid,
                    "type": servertypeselectelment.options[servertypeselectelment.options.selectedIndex].value
                }
            };
        }
        serverinfo.serverinfo.customFields = (typeof customFieldsObj !== 'undefined') ? customFieldsObj : '';
        //prepare customFields after creating server
        this.savedCustomFields = customFieldsUIObj;
        if (uid) {
            //prepare customFields after editing server
            this.servData[uid].customFields = customFieldsUIObj;
        }
        data_info = JSON.encode(serverinfo);
        var myJSON = new WFRequest.JSON({
            url: homeBase + "inc/server_list.php?" + AddUrlParam(),
            method: 'post',
            data: data_info,
            parameter: tr,
            parameter2: uid,
            urlEncoded: false,
            headers: {
                "Content-type": "application/json"
            },
            //onSuccess: function(jsonObj,text,obj){ (uid)?this.updateServer(jsonObj,text,obj):this.addNewServer(jsonObj,text,obj); }.bind(this)
            onSuccess: (uid) ? this.updateServer.bind(this) : this.addNewServer.bind(this)
        });
        myJSON.addEvent('onFailure', this.ajaxFailed);
        myJSON.send();
    },

    //updateServer:function(jsonObj,text,obj){
    updateServer: function (responseObj) {
        jsonObj = responseObj[1];
        text = responseObj[0];
        obj = responseObj[2];
        if (jsonObj.errcode !== 0) {
            var message = "";
            switch (jsonObj.errcode) {
            case 200:
            case 201:
            case 202:
            case 203:
            case 204:
            case 205:
            case 206:
                message += lang.label("errorcode_" + jsonObj.errcode);
                break;
            default:
                message += lang.label("errorcode_undefined");
            }
            //alert(lang.label('edit_scanserver_failed')+" ("+lang.label('error')+jsonObj.errcode+")");
            this.showMsg(lang.label('edit_scanserver_failed') + "<BR>" + message);
            if ($('update_or_add_save_button')){
                $('update_or_add_save_button').removeClass('disable');
            }
            return;
        }
        this.showhideEditDelete(false, true);
        this.servData[obj.options.parameter2].name = obj.options.parameter.getElementsByTagName('input')[0].value.toLowerCase();
        this.servData[obj.options.parameter2].account = obj.options.parameter.getElementsByTagName('input')[1].value;
        this.servData[obj.options.parameter2].password = obj.options.parameter.getElementsByTagName('input')[2].value;
        var servertypeselectelment = obj.options.parameter.getElementsByTagName('select')[0];
        this.servData[obj.options.parameter2].type = servertypeselectelment.options[servertypeselectelment.options.selectedIndex].value;
        this.servData[obj.options.parameter2].customFields = this.savedCustomFields ? this.savedCustomFields : {}
        g_serverlist.updateName(obj.options.parameter2, obj.options.parameter.getElementsByTagName('input')[0].value.toLowerCase(),this);
        // update row content
        $(obj.options.parameter2).cells[2].setHTML('<span title="'+lang.label(obj.options.parameter.getElementsByTagName('select')[0].value)+'">'+lang.label(obj.options.parameter.getElementsByTagName('select')[0].value)+'</span>');
        this.ajaxCount = 1;
        this.currentCount = 0;
        this.checkStatus(obj.options.parameter2, servertypeselectelment.options[servertypeselectelment.options.selectedIndex].value, true);
        this.waitingData();
        var dCheckbox = $(obj.options.parameter2).getElement('input.server_list');
        if (dCheckbox){
            dCheckbox.disabled = true;
        }

        //$(this.table_id).deleteRow(obj.options.parameter.rowIndex);
        $$('#serverlist_setting .addserver').set('styles',{'display':''});
        this.recoverButtons(obj.options.parameter2);
        if ($chk($(obj.options.parameter2).cells[1].getElement('img.status_img'))) {
            $(obj.options.parameter2).cells[1].getElement('img.status_img').src = homeBase + 'img/default/widgetLoading.gif';
        }
        var ServerNameorIP = $(obj.options.parameter2).cells[1].getElement('.ip');
        if ($chk(ServerNameorIP)) {
            ServerNameorIP.destroy();
            new Element('div', {'class':'ip ellipsis','title':changeLineForTip(this.servData[obj.options.parameter2].name, 70),
                'html':this.servData[obj.options.parameter2].name}).injectInside($(obj.options.parameter2).cells[1]);
        }
    },

    //addNewServer:function(jsonObj,text,obj){
    addNewServer: function (responseObj) {
        jsonObj = responseObj[1];
        text = responseObj[0];
        obj = responseObj[2];
        if (jsonObj.errcode !== 0) {
            var message = "";
            switch (jsonObj.errcode) {
            case 200:
            case 201:
            case 202:
            case 203:
            case 204:
            case 205:
            case 206:
                message += lang.label("errorcode_" + jsonObj.errcode);
                break;
            default:
                message += lang.label("errorcode_undefined");
            }
            ////alert(lang.label('add_scanserver_failed')+" ("+lang.label('error')+jsonObj.errcode+")");
            this.showMsg(lang.label('add_scanserver_failed') + "<BR>" + message);
            if ($('update_or_add_save_button')){
                $('update_or_add_save_button').removeClass('disable');
            }
            return;
        }
        this.showhideEditDelete(false, true);
        var uid = jsonObj.result;
        var servertypeselectelment = obj.options.parameter.getElementsByTagName('select')[0];
        // make a row in UI
        var item = {
            name: obj.options.parameter.getElementsByTagName('input')[0].value.toLowerCase(),
            type: servertypeselectelment.options[servertypeselectelment.options.selectedIndex].value,
            account: obj.options.parameter.getElementsByTagName('input')[1].value,
            password: obj.options.parameter.getElementsByTagName('input')[2].value? '*****':'',
            customFields: this.savedCustomFields ? this.savedCustomFields : {}
        };
        // sync data
        this.servData[uid] = item;
        var UriObj = parseUrl(obj.options.parameter.getElementsByTagName('input')[0].value.toLowerCase());
        g_serverlist.addOneServer({
            "id": uid,
            "name": obj.options.parameter.getElementsByTagName('input')[0].value.toLowerCase(),
            "lastcheck": 0,
            "hostinfo": {
                "host": UriObj.host.toLowerCase(),
                "port": UriObj.port,
                "type": servertypeselectelment.options[servertypeselectelment.options.selectedIndex].value,
                "customFields": this.savedCustomFields ? this.savedCustomFields : {},
                "protocol": UriObj.protocol.toLowerCase()
            }
        });
        // check status
        this.ajaxCount = 1;
        this.currentCount = 0;
        this.checkStatus(uid, servertypeselectelment.options[servertypeselectelment.options.selectedIndex].value, true);
        this.waitingData();
        // recover hidden buttons
        //$(this.table_id).deleteRow(obj.options.parameter.rowIndex);
        $$('#serverlist_setting .addserver').set('styles',{'display':''});
        this.recoverButtons('');
        // make a row for new server
        this.makeRow(item, uid);
        this.severlistModal.onResize();
    },


    // cancel the setitng of edit
    cancelServer: function (uid, element) {
        element.set('style',{'display':'block'});
        this.recoverButtons(uid);
    },

    // recover UI elements when editing is done
    recoverButtons: function (uid) {
        if (uid) { // edting a data
            $(uid).setStyle('display', '');
        } else { // adding new data
            this.adding = false;
            $(this.table_id).removeClass('adding');
        }
        $('add_server').set('styles',{'display':'block'});
        $('del_server').set('styles',{'display':'block'});
        $('refresh_server').set('styles',{'display':'block'});
    },

    // event of delete button
    deleteServer: function (e) {
        if (!this.isAjaxDone || $('enable_proxy').disabled === true) {
            return;
        }
        if (!confirm(lang.labelText('confirm_delete'))) {
            return;
        }
        var event = new Event(e);
        var uid = event.target.parentNode.parentNode.id;
        var tr = $(uid);

        // sent deleting data to server
        var myJSON = new WFRequest.JSON({
            url: homeBase + "inc/server_list.php?" + AddUrlParam(),
            method: 'post',
            parameter: tr,
            parameter2: uid,
            data: JSON.encode({
                "act": "delete",
                "serverid": uid
            }),
            urlEncoded: false,
            headers: {
                "Content-type": "application/json"
            },
            //onSuccess: function(jsonObj,text,obj){ this.deleteServerResponse(jsonObj,text,obj); }.bind(this)
            onSuccess: this.deleteServerResponse.bind(this)
        });
        myJSON.addEvent('onFailure', this.ajaxFailed);
        myJSON.send();
    },


    //deleteServerResponse:function(jsonObj,text,obj){
    deleteServerResponse: function (responseObj) {
        jsonObj = responseObj[1];
        text = responseObj[0];
        obj = responseObj[2];
        // UI refresh
        if (jsonObj.errcode !== 0) {
            var message = "";
            switch (jsonObj.errcode) {
            case 200:
            case 201:
            case 202:
            case 203:
            case 204:
            case 205:
            case 206:
                message += lang.label("errorcode_" + jsonObj.errcode);
                break;
            default:
                message += lang.label("errorcode_undefined");
            }
            //alert(lang.label('delete_scanserver_failed')+" ("+lang.label('error')+jsonObj.errcode+")");
            this.showMsg(lang.label('delete_scanserver_failed') + "<BR>" + message);
            return;
        }
        var arraylist = g_serverlist.getServerList();
        var arrServerList=obj.options.parameter.split(",");
        for (var i= 0,l=arrServerList.length; i< l; i++) {
            delete this.servData[arrServerList[i]];
            $(this.table_id).deleteRow($(arrServerList[i]).rowIndex);
            this.objSelectedServerHash.erase(arrServerList[i]);
loop:
            for (var index = arraylist.length - 1; index >= 0; index--) {
                if (arraylist[index].id == arrServerList[i]) {
                    g_serverlist.deleteOneServer(index);
                    break loop;
                }
            }
        }
        this.severlistModal.onResize();
        $('checkAll').checked=false;
        this.checkAll();
        this.tableRefresh();
    },

    //refresh the color of odd and even rows
    tableRefresh: function () {
        var rows = $(this.table_id).rows;
        var m = 0;
        var r = 1;
        $each(rows, function (item, index) {
            if (index === 0) {
                return true;
            }
            if (item.style.display === 'none') {
                // revert m and r if encounter a editing column
                r = 0;
                m = 1;
            }
            if (index % 2 == m) {
                item.addClass('even');
            } else if (index % 2 == r) {
                item.removeClass('even');
            }
        });
    },

    // waiting for ajax done and make message box
    waitingData: function () {
        this.isAjaxDone = false;
        this.waitHandler = setTimeout(function () {
            this.waitCheck();
        }.bind(this), 500);
    },
    waitCheck: function ()
	{
        // don't display error when check all serevrs
		//return;
        if (!this.isAjaxDone) {
            setTimeout(function () {
                this.waitCheck();
            }.bind(this), 500);
        } else if (this.lost_connection.length > 0 || this.timeout_connection.length > 0) {
            //making message box
            var msg_str = '';
            var timeoutmsg_str = '';
            var counter = 0;
            var timeoutcounter = 0;
            var displaymessage;
            $each(this.lost_connection, function (uid, i) {
                if (this.servData[uid] && this.servData[uid].name) {
                    msg_str += '<div>' + this.servData[uid].name.wordWrap(serverwrapcharscount, "<BR>") + '</div>';
                    counter++;
                }
            }.bind(this));
            if (counter > 0) {
                displaymessage = lang.label('failed_connect') + msg_str;
            }
            $each(this.timeout_connection, function (uid, i) {
                if (this.servData[uid] && this.servData[uid].name) {
                    timeoutmsg_str += '<div>' + this.servData[uid].name.wordWrap(serverwrapcharscount, "<BR>") + '</div>';
                    timeoutcounter++;
                }
            }.bind(this));
            if (counter > 0 && timeoutcounter > 0) {
               displaymessage = displaymessage + "<BR>" + lang.label('timeout_connect') + timeoutmsg_str;
            }
            else if (counter === 0 && timeoutcounter > 0) {
                displaymessage = lang.label('timeout_connect') + timeoutmsg_str;
            }
            if (counter > 0 || timeoutcounter > 0) {

                this.showMsg(displaymessage, 'error');

            }
            //showServerOffline();
            this.lost_connection = [];
            this.timeout_connection = [];
        }
    },


    // failed handler
    ajaxFailed: function () {
         if($('checkAll') === null){
            return;
         }
         $('checkAll').checked=false;
         this.checkAll();
    },

    renderUI: function(){
        var option = {
            id: 'modalServerList',
            title: lang.label('server_setting'),
            content: '',
            eventPosition: WF.util.iframeModaloffsetY(),
            onClose:this.clearServerListOnClose.bind(this),
            callBack: function(){
                //this.contentBox = $('serverlist_setting');
                this.onFinish();
            }.bind(this)
        };
        this.severlistModal = new WFModal(option);
    }
});
